#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by ZhangYichao on 2018/11/28
import json
import re

def getehrBaseJson():
    j = """{
        "id": 45657,
        "dateCreatedSys": "2014-05-12 00:00:00",
        "updateTime": "2018-11-09 19:17:37",
        "operatePerson": "朱夏媛",
        "operatePersonId": 240,
        "ehrId": "76384b47-fdc2-42ad-a374-3d5d090884e2",
        "ehrCode": "11010601300800188",
        "innerCode": "1040001807",
        "personName": "武舟英",
        "nameIndex": "WZY",
        "addrCity": "1101",
        "addrDistrict": "110106",
        "addrStreet": "110106013",
        "addrCommittee": "110106013008",
        "addrArea": "11010601300801",
        "addrCode": "110106013008011103179",
        "creatingOrgCode": "0604",
        "creatingOrgName": "方庄社区卫生服务中心",
        "creator": "王静",
        "creatorType": "1",
        "dutyDoctor": "刘景锋",
        "dateCreated": "2013-06-27",
        "gender": "2",
        "birthDate": "1959-05-04",
        "idNumber": "110103195905040342",
        "phoneNumber": "13501017053",
        "homeTel": "无",
        "householdType": "1",
        "accountType": "2",
        "bloodType": "2",
        "rhBloodType": "3",
        "payType": "1",
        "insuranceNumber": "10286933200X",
        "specialPeople": ",3,",
        "ehrIntegrity": 1,
        "death": "1",
        "cancelled": "1",
        "movedOut": "1",
        "mngOrgCode": "0604",
        "mngOrgName": "方庄社区卫生服务中心",
        "familyId": "19aa0d9b-093f-484e-b87b-69f01db32fcb",
        "hhRelationship": "1",
        "grHealth": "0",
        "grHighRisk": "0",
        "grChronicDisease": "1",
        "grOld": "0",
        "grMaternity": "0",
        "grChildren": "0",
        "grMentalDisorder": "0",
        "grHandicapped": "0",
        "cdHypertension": "1",
        "cdDiabetesMellitus": "1",
        "cdCoronaryDisease": "0",
        "cdCerebralApoplexy": "0",
        "cdCopd": "0",
        "cdTuberculosis": "0",
        "cdOther": "0",
        "familyName": "武舟英",
        "curContract": "1",
        "signTeamCode": "2a6fda7d-43f1-4579-ae09-bcada2eab1b7",
        "signTeamName": "方庄社区卫生服务中心刘景锋团队",
        "signTeamDoctor": "刘景锋",
        "lastMngDate": "2018-11-09",
        "familyMemberContact": "无",
        "familyMemberContactTel": "无",
        "firstAsm": "1",
        "regCity": "1",
        "regDistrict": "06",
        "regDetail": "",
        "verifyState": "1",
        "ruralNumber": "",
        "individualConStatus": "2",
        "isFamilyHealthCare": "2",
        "fileSpecification": 1
      }"""
    return j;

def getehrDetailsJson():
    j = """ {
        "id": 45657,
        "updateTime": "2018-07-24 13:56:00",
        "ehrId": "76384b47-fdc2-42ad-a374-3d5d090884e2",
        "curAddress": "丰台区方庄地区办事处芳群园二区社区居委会芳群园二区20号楼三单元2008",
        "hometown": "北京",
        "policeStation": "方庄",
        "idType": "1",
        "workUnit": "无",
        "officeTel": "不详",
        "contactorName": "李建国",
        "contactorPhone": "13501017053",
        "ethnicType": "1",
        "ethnicOther": "",
        "educationLevel": "5",
        "professionType": "9",
        "maritalStatus": "2",
        "payTypeDescription": "",
        "allergyHistory": "1",
        "allergyDescription": "",
        "exposureHistory": "1",
        "fhFather": "1",
        "fhMother": "1",
        "fhBrother": "1",
        "fhChildren": "1",
        "fhFatherDes": "",
        "fhMotherDes": "",
        "fhBrotherDes": "",
        "fhChildrenDes": "",
        "geneticHistory": "1",
        "geneticDescription": "",
        "disability": "1",
        "disabilityDescription": "",
        "leAirExhaust": "2",
        "leFuel": "3",
        "leWater": "1",
        "leWc": "3",
        "leLivestock": "4",
        "nationality": "1",
        "nationalityDescription": "",
        "nativePlace": "北京",
        "tempLicence": "1",
        "eMail": "无",
        "postalCode": "100078",
        "medicalUnit1": "东方医院",
        "medicalUnit2": "友谊医院",
        "medicalUnit3": "同仁医院",
        "medicalUnit4": "天坛医院",
        "smSmoking": "2",
        "smStart": "",
        "smEnd": "",
        "dkDrinking": "2",
        "dkEnd": "",
        "exExercise": "1",
        "exCycle": "1",
        "exTime": "1",
        "exType": "1",
        "fhType": "9",
        "fhAmount": "100",
        "slTime": "2",
        "slSituation": "8",
        "slDescription": "",
        "otherHabit": "无",
        "liveSituation": "2",
        "inmate": "2"
      }"""
    return j;

def getehrHfIndicator():
    j = """{
        "id": 45657,
        "updateTime": "2018-10-08 14:45:22",
        "ehrId": "76384b47-fdc2-42ad-a374-3d5d090884e2",
        "height": 170,
        "weight": 65,
        "waistline": 84,
        "hipline": 96,
        "bmi": 22.49,
        "whr": 0.87,
        "sbpL": 120,
        "dbpL": 70,
        "sbpR": 128,
        "dbpR": 84,
        "fbg": 6,
        "pbg": 8.6,
        "temperature": 36.4,
        "pulse": 80,
        "breathing": 20,
        "heartRate": 70,
        "hba1c": 6.4,
        "tc": 3.82,
        "tg": 1.19,
        "ldlC": 4,
        "hdlC": 1.57,
        "bun": 4.29,
        "cr": -1,
        "ccr": -1,
        "uran": "未查",
        "malb": 11,
        "ecg": "未查",
        "fundusOculi": "未查",
        "hgb": 134,
        "wbc": 4.9,
        "plt": 256,
        "pro": 0,
        "glu": 0,
        "ket": 0,
        "bld": 0,
        "fbgMgdl": -1,
        "alt": 29,
        "ast": 19,
        "alb": 45.2,
        "tbil": 16.7,
        "dbil": 2.7,
        "scr": 60,
        "kc": 4.16,
        "nc": 143
      }"""
    return j;

def getehrMedHistoryList():
    j="""{
          "id": 40834,
          "ehrId": "76384b47-fdc2-42ad-a374-3d5d090884e2",
          "historyType": "1",
          "optionType": "2",
          "occurrenceTime": "2012-09"
        }
    """
    return j
def getehrHProblemList():
    j="""{
          "id": 40471,
          "ehrId": "76384b47-fdc2-42ad-a374-3d5d090884e2",
          "problemName": "高血压",
          "startDate": "2012-09",
          "recordDate": "2013-06-27",
          "referralDoctor": "刘军兴"
        }
    """
    return j

def hump2underline(hunp_str):
    '''
    驼峰形式字符串转成下划线形式
    :param hunp_str: 驼峰形式字符串
    :return: 字母全小写的下划线形式字符串
    '''
    # 匹配正则，匹配小写字母和大写字母的分界位置
    p = re.compile(r'([a-z]|\d)([A-Z])')
    # 这里第二个参数使用了正则分组的后向引用
    sub = re.sub(p, r'\1_\2', hunp_str).lower()
    return sub

def underline2hump(underline_str):
    '''
    下划线形式字符串转成驼峰形式
    :param underline_str: 下划线形式字符串
    :return: 驼峰形式字符串
    '''
    # 这里re.sub()函数第二个替换参数用到了一个匿名回调函数，回调函数的参数x为一个匹配对象，返回值为一个处理后的字符串
    sub = re.sub(r'(_\w)',lambda x:x.group(1)[1].upper(),underline_str)
    return sub

def dict_to_json():
    dict = {}
    dict['name'] = 'many'
    dict['age'] = 10
    dict['sex'] = 'male'
    print(dict)  # 输出：{'name': 'many', 'age': 10, 'sex': 'male'}
    j = json.dumps(dict)
    print(j)  # 输出：{"name": "many", "age": 10, "sex": "male"}

def JSONehrBase(j,isarry):
    dict = json.loads(j)
    arryStr=""
    if isarry:
        arryStr="$.."
    for key in dict:
        print("""      <field>        
        <name>"""+key+"""</name>
        <path>"""+arryStr+key+"""</path>
        <type>None</type>
        <format/>
        <currency/>
        <decimal/>
        <group/>
        <length>-1</length>
        <precision>-1</precision>
        <trim_type>none</trim_type>
        <repeat>N</repeat>
      </field>""")



def hump2underlineEhrBase(j):
    dict = json.loads(j)
    for key in dict:
        print("""      <field> 
        <name>"""+key+"""</name>
        <rename>"""+hump2underline(key).upper()+"""</rename>
      </field>""")

if __name__ == '__main__':

    #JSONehrBase(getehrBaseJson())
    #JSONehrBase(getehrDetailsJson())
    #JSONehrBase(getehrHfIndicator())
    #JSONehrBase(getehrMedHistoryList(),True)
    #JSONehrBase(getehrHProblemList(),True)

    #hump2underlineEhrBase(getehrBaseJson())
    #hump2underlineEhrBase(getehrDetailsJson())
    #hump2underlineEhrBase(getehrHfIndicator())
    #hump2underlineEhrBase(getehrMedHistoryList())
    hump2underlineEhrBase(getehrHProblemList())